

#include "cassert.h"
#include "user_buffer.h"
#include "bluenrg_lp_evb_com.h"

#define PRINT_BUF (400)

static uint8_t write_fifo[1024+1];
static RingBuffer write_char_buf;



void COMPrintf_init(void)
{
  user_buffer_create(&write_char_buf, sizeof(write_fifo)-1, write_fifo);
  BSP_COM_Init(NULL);
}


/**
* @brief  Send Txt information message on LPUART Tx line (to PC Com port).
* @param  None
* @retval None
*/
void uart_write_str(uint8_t *paddr, uint16_t lenght)
{


}

void simulate_uart_write_fifo(uint8_t *pdata, uint16_t len)
{
    user_buffer_write_items(&write_char_buf,pdata,len);
}


// serial printf   uint64_t %llu
static uint8_t printf_buffer[PRINT_BUF] = {0};
int COMPrintf(const char* fmt, ...)
{
    va_list ap;
    va_start(ap, fmt );
    //memset(printf_buffer,'\0',sizeof(printf_buffer));
    uint16_t len = vsprintf((char *)printf_buffer,fmt,ap);
    va_end( ap );

    simulate_uart_write_fifo(printf_buffer,len);
    //uart_write_str(printf_buffer, len);
    return len;   
}

int COMPrintf_hexdump(uint8_t *parr,uint8_t len)
{
  char my_buf[PRINT_BUF];
  if(len < ((PRINT_BUF-1) /5))
  {
    memset(my_buf,0,sizeof(my_buf));
    for(int i=0;i<len;i++)
    {
       if((i+1)!=len)
         sprintf(my_buf+5*i,"0x%02x ",parr[i]);
       else
         sprintf(my_buf+5*i,"0x%02x \n",parr[i]);
    }
    COMPrintf(my_buf);
  }  
  
  return len;
}


void COMPrintfTick(void)
{
  
  if(user_buffer_item_count(&write_char_buf)){
    uint8_t buf[256];
    uint16_t  read_amount = user_buffer_peek(&write_char_buf, buf, sizeof(buf));
    BSP_COM_Write(buf, read_amount); 
    user_buffer_release_items(&write_char_buf, read_amount);
    
  }   
}





